package www.wmx.com.xssc.util.pdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import www.wmx.com.xssc.domain.vo.CommonShortXM;
import www.wmx.com.xssc.domain.vo.WcryShortXM;
import www.wmx.com.xssc.domain.vo.extract.request.LWRequest;
import www.wmx.com.xssc.domain.vo.extract.request.PatentRequest;
import www.wmx.com.xssc.domain.vo.extract.request.TSecretRequest;
import www.wmx.com.xssc.domain.vo.extract.request.ZZRequest;
import www.wmx.com.xssc.domain.vo.request.PDFRequest;
import www.wmx.com.xssc.domain.vo.response.JCYJJResponse;
import www.wmx.com.xssc.domain.vo.response.JSFMResponse;
import www.wmx.com.xssc.domain.vo.response.KJJBJResponse;
import www.wmx.com.xssc.domain.vo.response.WcryResonse;
import www.wmx.com.xssc.domain.vo.response.threeResponse.JCYJJAllResponse;
import www.wmx.com.xssc.domain.vo.response.threeResponse.JSFMJAllResponse;
import www.wmx.com.xssc.domain.vo.response.threeResponse.KJJBAllResponse;
import www.wmx.com.xssc.util.common.WcrReadUtil;
import www.wmx.com.xssc.util.enumUtil.CgjlType;
import www.wmx.com.xssc.util.enumUtil.TjdjEnum;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Slf4j
@Data
@Component
public class PDF {

    private int pageHeight = 2600; // 单页面高度
    private int pageWidth = 600; // 单页面宽度
    private BaseFont bf = null;
    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    //文件上传的根路径地址：
    private String basePath;
    //存储到数据库的相对路径：
    private String filePath;
    private String pdfName;

    private String bgNO;


    @Resource
    private WcrReadUtil wcrReadUtil;

    public PDF() {
        try {
            Properties properties = new Properties();
            // 读取my.properties配置文件到输入流中
            InputStream inputStream = PDF.class.getResourceAsStream("/config.properties");
            // 从输入流中加载属性列表
            properties.load(inputStream);
            this.basePath = properties.getProperty("file.upload.path");
            bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public File generatePDF(PDFRequest pdfRequest) {

        String[] split = UUID.randomUUID().toString().split("-");
        this.pdfName = Arrays.stream(split).collect(Collectors.joining());
        this.filePath = "/generate_file/"  + "xssc" + "/" +this.pdfName + ".pdf";
        String path = this.basePath + this.filePath;
        String fileDir = this.basePath + "/generate_file/"  + "xssc";
        log.info("形式审查报告的存储的绝对路径:{}", path);
        log.info("形式审查报告入库的相对路径:{}", filePath);
        File file = new File(path);
        File file0 = new File(fileDir);
        if (!file0.exists()) {
            boolean success = file0.mkdirs();
            if (!success) return null;
        }

        // 字体
        // Font fontfename = new Font(bf, 20, Font.BOLD, BaseColor.RED);
        Document document = null;
        PdfWriter writer = null;
        try {
            document = new Document(new Rectangle(pageWidth, pageHeight));

            writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            writer.setFullCompression();
            writer.setPdfVersion(PdfWriter.VERSION_1_4);
            writer.setPageEmpty(false);
            document.open();
            // --------------------page1
            createPage(document, writer, pdfRequest);
            // --------------------page1 end

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
//            if (writer != null)
//                 writer.close();
            if (document != null)
                document.close();
        }
        return file;
    }

    private void createPage(Document document, PdfWriter writer, PDFRequest pdfRequest) throws Exception {


        String nd = pdfRequest.getNd().substring(0, 4);

        Set<String> tjdwNameSet = pdfRequest.getTjdwNameSet();
        Set<String> wcdwNameSet = pdfRequest.getWcdwNameSet();

        int sizeJCYJJ = pdfRequest.getSizeJCYJJ();
        int sizeJSFMJ = pdfRequest.getSizeJSFMJ();
        int sizeKJJBJ = pdfRequest.getSizeKJJBJ();

        List<JCYJJAllResponse> jcyjjResponseList = pdfRequest.getJcyjjResponseList();
        List<JSFMJAllResponse> jsfmResponsesList = pdfRequest.getJsfmResponsesList();
        List<KJJBAllResponse> kjjbjResponseList = pdfRequest.getKjjbjResponseList();

        Map<Integer, CommonShortXM> idToXM = pdfRequest.getIdToXM();
        Map<String, Set<Integer>> tjdwToXmId = pdfRequest.getTjdwToXmId();
        Map<String, Set<Integer>> wcdwToXmId = pdfRequest.getWcdwToXmId();
        Set<String> tjdwkeySet = tjdwToXmId.keySet();
        Set<String> wcdwkeySet = wcdwToXmId.keySet();
        int sumAll = sizeJCYJJ + sizeJSFMJ + sizeKJJBJ;

        Font fontbr = new Font(bf, 12, Font.NORMAL);
        Font fontfront = new Font(bf, 12, Font.NORMAL);
        Font fontScore = new Font(bf, 16, Font.NORMAL);
        fontScore.setColor(BaseColor.RED);

        Paragraph brnone = new Paragraph(" ", fontbr);
        // --------------------page1
        Paragraph title1 = null;
        // 文件名称
        title1 = new Paragraph(nd + "年度 —— 形式审查检测报告", new Font(bf, 20, Font.BOLD));
        title1.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(title1);
        document.add(brnone);
        document.add(brnone);
        document.add(new Paragraph("\n\n")); // 或者使用多个Paragraph对象

        // 密级
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase("形式审查报告编号：" + UUID.randomUUID().toString().replaceAll("-", ""), fontfront), 90F,
                document.top() - 50, 0);

        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase("报告生成时间：" + DATE_FORMAT.format(LocalDate.now()), fontfront), 90F,
                document.top() - 70, 0);

        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase("报奖总数量：" + sumAll, fontfront), 90F,
                document.top() - 90, 0);
        // 密级
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase("● 基础研究奖共： " + sizeJCYJJ + " 项，其中不合格：" + jcyjjResponseList.size() + " 项", fontfront), 90F,
                document.top() - 110, 0);
        // 文档编号
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase("● 技术发明奖共： " + sizeJSFMJ + " 项，其中不合格：" + jsfmResponsesList.size() + " 项", fontfront), 90F,
                document.top() - 130, 0);
        // 版本号
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase("● 科技进步奖共： " + sizeKJJBJ + " 项，其中不合格：" + kjjbjResponseList.size() + " 项", fontfront), 90F,
                document.top() - 150, 0);
        // 版本号
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase("● 推荐单位共： " + tjdwNameSet.size() + " 家，其中不合格：" + tjdwkeySet.size() + " 家", fontfront), 90F,
                document.top() - 170, 0);
        // 版本号
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase("● 完成单位共： " + wcdwNameSet.size() + " 家，其中不合格：" + wcdwkeySet.size() + " 家", fontfront), 90F,
                document.top() - 190, 0);

        // 添加的是换行符号：
        document.add(brnone);
        document.add(brnone);
        document.add(brnone);
        document.add(new Paragraph("\n\n")); // 或者使用多个Paragraph对象

        title1 = new Paragraph("一、推荐单位不合格清单", new Font(bf, 14, Font.NORMAL));
        title1.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(title1);
        document.add(brnone);

        // ---------------------------下面是第一个表格--------------------------------------

        float[] widthsTitle = {10f, 15f, 15f, 20f, 20f, 20f};
        PdfPTable tableTitle = new PdfPTable(widthsTitle);
        tableTitle.setWidthPercentage(100f);
        tableTitle.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);

        // 序号    推荐单位名称      不合格数          基础研究奖不合格数       技术发明奖不合格数       科技进步奖不合格数
        PdfPCell cellTitle = new PdfPCell(new Phrase("序号", fontbr));
        cellTitle.setBorderWidth(0.5f);
        cellTitle.setUseAscender(true);
        cellTitle.setUseDescender(true);
        cellTitle.setVerticalAlignment(PdfPTable.ALIGN_MIDDLE);
        cellTitle.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
        tableTitle.addCell(cellTitle);
        cellTitle.setPhrase(new Phrase(new Phrase("推荐单位名称", fontbr)));
        tableTitle.addCell(cellTitle);
        cellTitle.setPhrase(new Phrase(new Phrase("不合格数", fontbr)));
        tableTitle.addCell(cellTitle);
        cellTitle.setPhrase(new Phrase(new Phrase("基础研究奖不合格数", fontbr)));
        tableTitle.addCell(cellTitle);
        cellTitle.setPhrase(new Phrase(new Phrase("技术发明奖不合格数", fontbr)));
        tableTitle.addCell(cellTitle);
        cellTitle.setPhrase(new Phrase(new Phrase("科技进步奖不合格数", fontbr)));
        tableTitle.addCell(cellTitle);
        //下面就是所有的推荐单位：
        int indexTJDW = 1;
        for (String tjdwName : tjdwkeySet) {
            Set<Integer> xmIdList = tjdwToXmId.get(tjdwName);
            int jcyjjNumFail = 0;
            int jsfmjNumFail = 0;
            int kjjbjNumFail = 0;
            for (Integer xmId : xmIdList) {
                CommonShortXM commonShortXM = idToXM.get(xmId);
                if (commonShortXM.getCgjlType() == CgjlType.JCYJJ.getCode()) {
                    jcyjjNumFail++;
                } else if (commonShortXM.getCgjlType() == CgjlType.JSFMJ.getCode()) {
                    jsfmjNumFail++;
                } else {
                    kjjbjNumFail++;
                }
            }
            cellTitle.setPhrase(new Phrase(new Phrase(indexTJDW++ + "", fontbr)));
            tableTitle.addCell(cellTitle);
            cellTitle.setPhrase(new Phrase(new Phrase(tjdwName, fontbr)));
            tableTitle.addCell(cellTitle);
            cellTitle.setPhrase(new Phrase(new Phrase(String.valueOf(xmIdList.size()), fontbr)));
            tableTitle.addCell(cellTitle);
            cellTitle.setPhrase(new Phrase(new Phrase(String.valueOf(jcyjjNumFail), fontbr)));
            tableTitle.addCell(cellTitle);
            cellTitle.setPhrase(new Phrase(new Phrase(String.valueOf(jsfmjNumFail), fontbr)));
            tableTitle.addCell(cellTitle);
            cellTitle.setPhrase(new Phrase(new Phrase(String.valueOf(kjjbjNumFail), fontbr)));
            tableTitle.addCell(cellTitle);
        }
        document.add(tableTitle);

        // 添加的是换行符号：
        document.add(brnone);
        document.add(brnone);
        document.add(new Paragraph("\n\n")); // 或者使用多个Paragraph对象

        // ---------------------------下面是第二个表格--------------------------------------
        float[] widths = {100f};
        PdfPTable table = new PdfPTable(widths);
        table.setWidthPercentage(100f);
        table.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
        PdfPCell cell = new PdfPCell(new Phrase("推荐单位列表", fontbr));
        cell.setBorderWidth(0.5f);
        cell.setUseAscender(true);
        cell.setUseDescender(true);
        cell.setVerticalAlignment(PdfPTable.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
        table.addCell(cell);
        //
        int tjdwID = 1;
        for (Map.Entry<String, Set<Integer>> entry : tjdwToXmId.entrySet()) {
            StringBuilder sb = new StringBuilder();
            String tjdwName = entry.getKey();
            Set<Integer> xmIdList = entry.getValue();
            int id = 1;
            sb.append(tjdwID++ + ".推荐单位名称:" + tjdwName + "，不合格总数:" + xmIdList.size() + "\n");
            for (Integer xmId : xmIdList) {
                CommonShortXM commonShortXM = idToXM.get(xmId);
                String xmmc = commonShortXM.getXmmc();
                String tjdj = commonShortXM.getTjdj();
                int cgjlType = commonShortXM.getCgjlType();
                String message = CgjlType.getByCode(cgjlType).getMessage();
//                1.   推荐单位名称：_______，不合格总数:__
//                    （1）推荐奖项：基础研究奖，项目名称：_______,推荐等级_,编号_
                sb.append("    （" + id++ + "）推荐奖项：").append(message)
                        .append("，项目名称：").append(xmmc).append("，推荐等级：")
                        .append(getTJDJMessage(tjdj)).append("，项目编号：").append(xmId).append("\n");

            }
            cell.setPhrase(new Phrase(new Phrase(sb.toString(), fontbr)));
            table.addCell(cell);
        }
        document.add(table);
        // 添加的是换行符号：
        document.add(brnone);
        document.add(brnone);
        document.add(new Paragraph("\n\n")); // 或者使用多个Paragraph对象


        title1 = new Paragraph("二、完成单位不合格清单", new Font(bf, 14, Font.NORMAL));
        title1.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(title1);
        document.add(brnone);

        // ---------------------------下面是第三个表格--------------------------------------

        float[] widthsTitle2 = {10f, 15f, 15f, 20f, 20f, 20f};
        PdfPTable tableTitle2 = new PdfPTable(widthsTitle2);
        tableTitle2.setWidthPercentage(100f);
        tableTitle2.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);

        // 序号    推荐单位名称      不合格数          基础研究奖不合格数       技术发明奖不合格数       科技进步奖不合格数
        PdfPCell cellTitle2 = new PdfPCell(new Phrase("序号", fontbr));
        cellTitle2.setBorderWidth(0.5f);
        cellTitle2.setUseAscender(true);
        cellTitle2.setUseDescender(true);
        cellTitle2.setVerticalAlignment(PdfPTable.ALIGN_MIDDLE);
        cellTitle2.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
        tableTitle2.addCell(cellTitle2);
        cellTitle2.setPhrase(new Phrase(new Phrase("完成单位名称", fontbr)));
        tableTitle2.addCell(cellTitle2);
        cellTitle2.setPhrase(new Phrase(new Phrase("不合格数", fontbr)));
        tableTitle2.addCell(cellTitle2);
        cellTitle2.setPhrase(new Phrase(new Phrase("基础研究奖不合格数", fontbr)));
        tableTitle2.addCell(cellTitle2);
        cellTitle2.setPhrase(new Phrase(new Phrase("技术发明奖不合格数", fontbr)));
        tableTitle2.addCell(cellTitle2);
        cellTitle2.setPhrase(new Phrase(new Phrase("科技进步奖不合格数", fontbr)));
        tableTitle2.addCell(cellTitle2);
        //下面就是所有的推荐单位：
        int indexWCDW = 1;
        for (String wcdwName : wcdwkeySet) {
            Set<Integer> xmIdList = wcdwToXmId.get(wcdwName);
            int jcyjjNumFail = 0;
            int jsfmjNumFail = 0;
            int kjjbjNumFail = 0;
            for (Integer xmId : xmIdList) {
                CommonShortXM commonShortXM = idToXM.get(xmId);
                if (commonShortXM.getCgjlType() == CgjlType.JCYJJ.getCode()) {
                    jcyjjNumFail++;
                } else if (commonShortXM.getCgjlType() == CgjlType.JSFMJ.getCode()) {
                    jsfmjNumFail++;
                } else {
                    kjjbjNumFail++;
                }
            }
            cellTitle2.setPhrase(new Phrase(new Phrase(indexWCDW++ + "", fontbr)));
            tableTitle2.addCell(cellTitle2);
            cellTitle2.setPhrase(new Phrase(new Phrase(wcdwName, fontbr)));
            tableTitle2.addCell(cellTitle2);
            cellTitle2.setPhrase(new Phrase(new Phrase(String.valueOf(xmIdList.size()), fontbr)));
            tableTitle2.addCell(cellTitle2);
            cellTitle2.setPhrase(new Phrase(new Phrase(String.valueOf(jcyjjNumFail), fontbr)));
            tableTitle2.addCell(cellTitle2);
            cellTitle2.setPhrase(new Phrase(new Phrase(String.valueOf(jsfmjNumFail), fontbr)));
            tableTitle2.addCell(cellTitle2);
            cellTitle2.setPhrase(new Phrase(new Phrase(String.valueOf(kjjbjNumFail), fontbr)));
            tableTitle2.addCell(cellTitle2);
        }
        document.add(tableTitle2);

        // 添加的是换行符号：
        document.add(brnone);
        document.add(brnone);
        document.add(new Paragraph("\n\n")); // 或者使用多个Paragraph对象

        // ---------------------------下面是第四个表格--------------------------------------
        float[] widthsWCDW = {100f};
        PdfPTable tableWCDW = new PdfPTable(widthsWCDW);
        tableWCDW.setWidthPercentage(100f);
        tableWCDW.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
        PdfPCell cellWCDW = new PdfPCell(new Phrase("完成单位列表", fontbr));
        cellWCDW.setBorderWidth(0.5f);
        cellWCDW.setUseAscender(true);
        cellWCDW.setUseDescender(true);
        cellWCDW.setVerticalAlignment(PdfPTable.ALIGN_MIDDLE);
        cellWCDW.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
        tableWCDW.addCell(cellWCDW);
        //
        int wcdwID = 1;
        for (Map.Entry<String, Set<Integer>> entry : wcdwToXmId.entrySet()) {
            StringBuilder sb = new StringBuilder();
            String wcdwName = entry.getKey();
            Set<Integer> xmIdList = entry.getValue();
            int id = 1;
            sb.append(wcdwID++ + ".完成单位名称:" + wcdwName + "，不合格总数:" + xmIdList.size() + "\n");
            for (Integer xmId : xmIdList) {
                CommonShortXM commonShortXM = idToXM.get(xmId);
                String xmmc = commonShortXM.getXmmc();
                String tjdj = commonShortXM.getTjdj();
                int cgjlType = commonShortXM.getCgjlType();
                String message = CgjlType.getByCode(cgjlType).getMessage();
//                1.   推荐单位名称：_______，不合格总数:__
//                    （1）推荐奖项：基础研究奖，项目名称：_______,推荐等级_,编号_
                sb.append("    （" + id++ + "）推荐奖项：").append(message)
                        .append("，项目名称：").append(xmmc).append("，推荐等级：")
                        .append(getTJDJMessage(tjdj)).append("，项目编号：").append(xmId).append("\n");

            }
            cellWCDW.setPhrase(new Phrase(new Phrase(sb.toString(), fontbr)));
            tableWCDW.addCell(cellWCDW);
        }
        document.add(tableWCDW);
        // 添加的是换行符号：
        document.add(brnone);
        document.add(brnone);
        document.add(new Paragraph("\n\n")); // 或者使用多个Paragraph对象


        title1 = new Paragraph("三、不合格原因分析（推荐项目为单位）", new Font(bf, 14, Font.NORMAL));
        title1.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(title1);
        document.add(brnone);

        // ---------------------------下面是第五个表格，展示每个项目的信息：--------------------------------------
        float[] widthsXM = {100f};
        PdfPTable tableXM = new PdfPTable(widthsXM);
        tableXM.setWidthPercentage(100f);
        tableXM.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
        PdfPCell cellXM = new PdfPCell(new Phrase("项目列表", fontbr));
        cellXM.setBorderWidth(0.5f);
        cellXM.setUseAscender(true);
        cellXM.setUseDescender(true);
        cellXM.setVerticalAlignment(PdfPTable.ALIGN_MIDDLE);
        cellXM.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
        tableXM.addCell(cellXM);


        List<String> jcyjjFailReason = getJCYJJFailReason(jcyjjResponseList, idToXM);
        List<String> jsfmjFailReason = getJSFMJFailReason(jsfmResponsesList, idToXM);
        List<String> kjjbjFailReason = getKJJBJFailReason(kjjbjResponseList, idToXM);
        for (String s : jcyjjFailReason) {
            cellXM.setPhrase(new Phrase(new Phrase(s, fontbr)));
            tableXM.addCell(cellXM);
        }
        for (String s : jsfmjFailReason) {
            cellXM.setPhrase(new Phrase(new Phrase(s, fontbr)));
            tableXM.addCell(cellXM);
        }
        for (String s : kjjbjFailReason) {
            cellXM.setPhrase(new Phrase(new Phrase(s, fontbr)));
            tableXM.addCell(cellXM);
        }

        document.add(tableXM);
        document.add(brnone);
        document.add(new Paragraph("\n")); // 或者使用多个Paragraph对象

        title1 = new Paragraph("---------------------------------------------------------------------------------------", new Font(bf, 14, Font.NORMAL));
        title1.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(title1);
        document.add(brnone);

        title1 = new Paragraph("本报告为检测系统自动生成，仅供参考", new Font(bf, 10, Font.NORMAL));
        title1.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(title1);


        title1 = new Paragraph("说明：", new Font(bf, 10, Font.NORMAL));
        title1.setAlignment(Paragraph.ALIGN_LEFT);
        document.add(title1);

        title1 = new Paragraph("    1.项目编号为（三、不合格原因分析）项目；列表中顺序编号", new Font(bf, 10, Font.NORMAL));
        title1.setAlignment(Paragraph.ALIGN_LEFT);
        document.add(title1);

    }

    private List<String> getJCYJJFailReason(List<JCYJJAllResponse> jcyjjResponseList, Map<Integer, CommonShortXM> idToXM) {

        List<String> failReasonList = new ArrayList<>();
        for (JCYJJAllResponse jcyjjAllResponse : jcyjjResponseList) {
            StringBuilder sb = new StringBuilder();
            int xmId = jcyjjAllResponse.getId();
            CommonShortXM commonShortXM = idToXM.get(xmId);
            sb.append(xmId + ".项目名称:" + commonShortXM.getXmmc() +"\n  推荐奖项:" + CgjlType.getByCode(commonShortXM.getCgjlType()).getMessage() + "\n  推荐等级：" + getTJDJMessage(commonShortXM.getTjdj()) + "\n  推荐单位："
                    + commonShortXM.getTjdwList().stream().reduce((a, b) -> a + "、" + b).orElse(""));
            sb.append("\n");
            List<String> wcdwList = commonShortXM.getWcdwList();
            if (wcdwList != null && !wcdwList.isEmpty()) {
                sb.append("  完成单位：");
                for (int i = 0; i < wcdwList.size(); i++) {
                    if (i != wcdwList.size() - 1) {
                        sb.append(wcdwList.get(i) + ",");
                    } else {
                        sb.append(wcdwList.get(i) + "\n");
                    }
                }
            }
            LocalDateTime xmBeginTime = commonShortXM.getXmBeginTime();
            LocalDateTime xmEndTime = commonShortXM.getXmEndTime();
            sb.append("  项目起止时间：").append(DATE_FORMAT.format(xmBeginTime)).append("-").append(DATE_FORMAT.format(xmEndTime)).append("\n");
            List<WcryShortXM> wcryShortXMS = wcrReadUtil.getWcryFilterByTypeAndId(commonShortXM.getCgjlType(), commonShortXM.getJbxxID());
            if (wcryShortXMS != null && !wcryShortXMS.isEmpty()) {
                sb.append("  项目完成人员：");
                for (int i = 0; i < wcryShortXMS.size(); i++) {
                    String xm = wcryShortXMS.get(i).getXm();
                    if (i != wcryShortXMS.size() - 1) {
                        sb.append(xm + ",");
                    } else {
                        sb.append(xm + "\n");
                    }
                }
            }
            sb.append("  不合格原因：\n");
            int failId = 1;
            JCYJJResponse jcyjjResponse = jcyjjAllResponse.getJcyjjResponse();
            //两个人员的限制失败原因：
            String rsLimitReason = jcyjjAllResponse.getRsLimitReason();
            if (rsLimitReason != null) {
                sb.append("  (" + failId++ + ")" + rsLimitReason + "\n");
            }
            //单位限制失败原因：
            String dwLimitReason = jcyjjAllResponse.getDwLimitReason();
            if (dwLimitReason != null) {
                sb.append("  (" + failId++ + ")" + dwLimitReason + "\n");
            }
            //推荐等级的失败原因：
            String tjdjFailReason = jcyjjAllResponse.getTjdjFailReason();
            if (tjdjFailReason != null) {
                sb.append("  (" + failId++ + ")" + tjdjFailReason + "\n");
            }
            //成果登记失败原因：
            String cgdjFailReson = jcyjjResponse.getCgdjFailReson();
            if (cgdjFailReson != null) {
                sb.append("  (" + failId++ + ")" + cgdjFailReson + "\n");
            }
            //各个成果的失败原因：
            List<LWRequest> lwRequestList = jcyjjResponse.getLwRequestList();
            if (lwRequestList != null && !lwRequestList.isEmpty()) {
                for (LWRequest lwRequest : lwRequestList) {
                    sb.append("  (" + failId++ + ")" + "论文：<<" + lwRequest.getLwtm() + ">> 不合格项：\n");
                    List<String> reason = lwRequest.getFailReason();
                    for (String s : reason) {
                        sb.append("  " + s + ";\n");
                    }

                }
            }
            List<PatentRequest> zlRequestList = jcyjjResponse.getZlRequestList();
            if (zlRequestList != null && !zlRequestList.isEmpty()) {
                for (PatentRequest patentRequest : zlRequestList) {
                    sb.append("  (" + failId++ + ")" + "专利：<<" + patentRequest.getZlmc() + ">> 不合格项：\n");
                    List<String> reason = patentRequest.getFailReason();
                    for (String s : reason) {
                        sb.append("  " + s + ";\n");
                    }
                }
            }
            List<ZZRequest> zzRequestList = jcyjjResponse.getZzRequestList();
            if (zzRequestList != null && !zzRequestList.isEmpty()) {
                for (ZZRequest zzRequest : zzRequestList) {
                    sb.append("  (" + failId++ + ")" + "著作：<<" + zzRequest.getZzmc() + ">> 不合格项：\n");
                    List<String> reason = zzRequest.getFailReason();
                    for (String s : reason) {
                        sb.append("  " + s + ";\n");
                    }
                }
            }
            //完成人员失败的原因：
            List<WcryResonse> wcryResonseList = jcyjjAllResponse.getWcryResonseList();
            if (wcryResonseList != null && !wcryResonseList.isEmpty()) {
                for (WcryResonse wcryResonse : wcryResonseList) {
                    WcryShortXM wcryShortXM = wcryResonse.getWcryShortXM();
                    String xm = wcryShortXM.getXm();
                    String xb = wcryShortXM.getXb();
                    String zw = wcryShortXM.getZw();
                    String dwid = wcryShortXM.getDwid();
                    int sum = 0;
                    if (wcryResonse.getOtherJCYJJXM() != null && !wcryResonse.getOtherJCYJJXM().isEmpty()) {
                        sum += wcryResonse.getOtherJCYJJXM().size();
                    }
                    if (wcryResonse.getOtherJSFMJXM() != null && !wcryResonse.getOtherJSFMJXM().isEmpty()) {
                        sum += wcryResonse.getOtherJSFMJXM().size();
                    }
                    if (wcryResonse.getOtherKJJBJXM() != null && !wcryResonse.getOtherKJJBJXM().isEmpty()) {
                        sum += wcryResonse.getOtherKJJBJXM().size();
                    }
                    wcryResonse.getOtherKJJBJXM();
                    sb.append("  (" + failId++ + ")" + "完成人员：" + xm + "," + xb + "," + zw + "," + dwid + ",当前年度参评奖项为:" + sum + "项超过做大限额\n");
                }
            }
            failReasonList.add(sb.toString());
        }
        return failReasonList;
    }

    private List<String> getJSFMJFailReason(List<JSFMJAllResponse> jsfmResponsesList, Map<Integer, CommonShortXM> idToXM) {

        List<String> failReasonList = new ArrayList<>();
        for (JSFMJAllResponse jsfmjAllResponse : jsfmResponsesList) {
            StringBuilder sb = new StringBuilder();
            int xmId = jsfmjAllResponse.getId();
            CommonShortXM commonShortXM = idToXM.get(xmId);
            sb.append(xmId + ".项目名称:" + commonShortXM.getXmmc() + "\n" + "  推荐奖项:" + CgjlType.getByCode(commonShortXM.getCgjlType()).getMessage() + "\n  推荐等级：" + getTJDJMessage(commonShortXM.getTjdj()) + "\n  推荐单位："
                    + commonShortXM.getTjdwList().stream().reduce((s1, s2) -> s1 + "、" + s2).orElse(""));
            sb.append("\n");
            List<String> wcdwList = commonShortXM.getWcdwList();
            if (wcdwList != null && !wcdwList.isEmpty()) {
                sb.append("  完成单位：");
                for (int i = 0; i < wcdwList.size(); i++) {
                    if (i != wcdwList.size() - 1) {
                        sb.append(wcdwList.get(i) + ",");
                    } else {
                        sb.append(wcdwList.get(i) + "\n");
                    }
                }
            }
            LocalDateTime xmBeginTime = commonShortXM.getXmBeginTime();
            LocalDateTime xmEndTime = commonShortXM.getXmEndTime();
            sb.append("  项目起止时间：").append(DATE_FORMAT.format(xmBeginTime)).append("-").append(DATE_FORMAT.format(xmEndTime)).append("\n");
            List<WcryShortXM> wcryShortXMS = wcrReadUtil.getWcryFilterByTypeAndId(commonShortXM.getCgjlType(), commonShortXM.getJbxxID());
            if (wcryShortXMS != null && !wcryShortXMS.isEmpty()) {
                sb.append("  项目完成人员：");
                for (int i = 0; i < wcryShortXMS.size(); i++) {
                    String xm = wcryShortXMS.get(i).getXm();
                    if (i != wcryShortXMS.size() - 1) {
                        sb.append(xm + ",");
                    } else {
                        sb.append(xm + "\n");
                    }
                }
            }
            sb.append("  不合格原因：\n");
            int failId = 1;
            JSFMResponse jsfmResponse = jsfmjAllResponse.getJsfmResponse();
            //两个数量的限制：
            String rsLimitReason = jsfmjAllResponse.getRsLimitReason();
            if (rsLimitReason != null) {
                sb.append("  (" + failId++ + ")" + rsLimitReason + "\n");
            }
            //推荐等级的失败原因：
            String tjdjFailReason = jsfmjAllResponse.getTjdjFailReason();
            if (tjdjFailReason != null) {
                sb.append("  (" + failId++ + ")" + tjdjFailReason + "\n");
            }
            //成果登记失败原因：
            String cgdjFailReson = jsfmResponse.getCgdjFailReson();
            if (cgdjFailReson != null) {
                sb.append("  (" + failId++ + ")" + cgdjFailReson + "\n");
            }
            //各个成果的失败原因：
            List<LWRequest> lwRequestList = jsfmResponse.getLwRequestList();
            if (lwRequestList != null && !lwRequestList.isEmpty()) {
                for (LWRequest lwRequest : lwRequestList) {
                    sb.append("  (" + failId++ + ")" + "论文：<<" + lwRequest.getLwtm() + ">> 不合格项：\n");
                    List<String> reason = lwRequest.getFailReason();
                    for (String s : reason) {
                        sb.append("  " + s + ";\n");
                    }

                }
            }
            List<PatentRequest> zlRequestList = jsfmResponse.getZlRequestList();
            if (zlRequestList != null && !zlRequestList.isEmpty()) {
                for (PatentRequest patentRequest : zlRequestList) {
                    sb.append("  (" + failId++ + ")" + "专利：<<" + patentRequest.getZlmc() + ">> 不合格项：\n");
                    List<String> reason = patentRequest.getFailReason();
                    for (String s : reason) {
                        sb.append("  " + s + ";\n");
                    }
                }
            }
            List<ZZRequest> zzRequestList = jsfmResponse.getZzRequestList();
            if (zzRequestList != null && !zzRequestList.isEmpty()) {
                for (ZZRequest zzRequest : zzRequestList) {
                    sb.append("  (" + failId++ + ")" + "著作：<<" + zzRequest.getZzmc() + ">> 不合格项：\n");
                    List<String> reason = zzRequest.getFailReason();
                    for (String s : reason) {
                        sb.append("  " + s + ";\n");
                    }
                }
            }
            List<TSecretRequest> tSecretRequestList = jsfmResponse.getTSecretRequestList();
            if (tSecretRequestList != null && !tSecretRequestList.isEmpty()) {
                for (TSecretRequest tSecretRequest : tSecretRequestList) {
                    sb.append("  (" + failId++ + ")" + "技术秘密：<<" + tSecretRequest.getMc() + ">> 不合格项：\n");
                    List<String> reason = tSecretRequest.getFailReason();
                    for (String s : reason) {
                        sb.append("  " + s + ";\n");
                    }
                }
            }
            //完成人员失败的原因：
            List<WcryResonse> wcryResonseList = jsfmjAllResponse.getWcryResonseList();
            if (wcryResonseList != null && !wcryResonseList.isEmpty()) {
                for (WcryResonse wcryResonse : wcryResonseList) {
                    WcryShortXM wcryShortXM = wcryResonse.getWcryShortXM();
                    String xm = wcryShortXM.getXm();
                    String xb = wcryShortXM.getXb();
                    String zw = wcryShortXM.getZw();
                    String dwid = wcryShortXM.getDwid();
                    int sum = 0;
                    if (wcryResonse.getOtherJCYJJXM() != null && !wcryResonse.getOtherJCYJJXM().isEmpty()) {
                        sum += wcryResonse.getOtherJCYJJXM().size();
                    }
                    if (wcryResonse.getOtherJSFMJXM() != null && !wcryResonse.getOtherJSFMJXM().isEmpty()) {
                        sum += wcryResonse.getOtherJSFMJXM().size();
                    }
                    if (wcryResonse.getOtherKJJBJXM() != null && !wcryResonse.getOtherKJJBJXM().isEmpty()) {
                        sum += wcryResonse.getOtherKJJBJXM().size();
                    }
                    wcryResonse.getOtherKJJBJXM();
                    sb.append("  (" + failId++ + ")" + "完成人员：" + xm + "," + xb + "," + zw + "," + dwid + ",当前年度参评奖项为:" + sum + "项超过做大限额\n");
                }
            }
            failReasonList.add(sb.toString());
        }
        return failReasonList;
    }

    private List<String> getKJJBJFailReason(List<KJJBAllResponse> kjjbjResponseList, Map<Integer, CommonShortXM> idToXM) {
        List<String> failReasonList = new ArrayList<>();
        for (KJJBAllResponse kjjbAllResponse : kjjbjResponseList) {
            StringBuilder sb = new StringBuilder();

            int xmId = kjjbAllResponse.getId();
            CommonShortXM commonShortXM = idToXM.get(xmId);
            sb.append(xmId + ".项目名称:"+commonShortXM.getXmmc()+"\n" + "  推荐奖项:" + CgjlType.getByCode(commonShortXM.getCgjlType()).getMessage() + "\n  推荐等级：" + getTJDJMessage(commonShortXM.getTjdj()) + "\n  推荐单位："
                    + commonShortXM.getTjdwList().stream().reduce((s1, s2) -> s1 + "、" + s2).orElse(""));
            sb.append("\n");
            List<String> wcdwList = commonShortXM.getWcdwList();
            if (wcdwList != null && !wcdwList.isEmpty()) {
                sb.append("  完成单位：");
                for (int i = 0; i < wcdwList.size(); i++) {
                    if (i != wcdwList.size() - 1) {
                        sb.append(wcdwList.get(i) + ",");
                    } else {
                        sb.append(wcdwList.get(i) + "\n");
                    }
                }
            }
            LocalDateTime xmBeginTime = commonShortXM.getXmBeginTime();
            LocalDateTime xmEndTime = commonShortXM.getXmEndTime();
            sb.append("  项目起止时间：").append(DATE_FORMAT.format(xmBeginTime)).append("-").append(DATE_FORMAT.format(xmEndTime)).append("\n");
            List<WcryShortXM> wcryShortXMS = wcrReadUtil.getWcryFilterByTypeAndId(commonShortXM.getCgjlType(), commonShortXM.getJbxxID());
            if (wcryShortXMS != null && !wcryShortXMS.isEmpty()) {
                sb.append("  项目完成人员：");
                for (int i = 0; i < wcryShortXMS.size(); i++) {
                    String xm = wcryShortXMS.get(i).getXm();
                    if (i != wcryShortXMS.size() - 1) {
                        sb.append(xm + ",");
                    } else {
                        sb.append(xm + "\n");
                    }
                }
            }
            sb.append("  不合格原因：\n");
            int failId = 1;
            KJJBJResponse kjjbjResponse = kjjbAllResponse.getKjjbjResponse();
            //两项数量的限制：
            String rsLimitReason = kjjbAllResponse.getRsLimitReason();
            if (rsLimitReason != null) {
                sb.append("  (" + failId++ + ")" + rsLimitReason + "\n");
            }
            String dwLimitReason = kjjbAllResponse.getDwLimitReason();
            if (dwLimitReason != null) {
                sb.append("  (" + failId++ + ")" + dwLimitReason + "\n");
            }
            //推荐等级的失败原因：
            List<String> jjxyFailReason = kjjbjResponse.getFailReason();
            String xmTjdj = commonShortXM.getTjdj();
            Integer tjdj = Integer.parseInt(xmTjdj.substring(xmTjdj.length() - 1));
            if (jjxyFailReason != null && !jjxyFailReason.isEmpty()) {
                sb.append("  (" + failId++ + ")" + "推荐等级：" + TjdjEnum.getByCode(tjdj).getMessage() + " 不合格项：\n");
                for (String reason : jjxyFailReason) {
                    sb.append("  " + reason + ";\n");
                }
            }
            //成果登记失败原因：
            String cgdjFailReson = kjjbjResponse.getCgdjFailReson();
            if (cgdjFailReson != null) {
                sb.append("  (" + failId++ + ")" + cgdjFailReson + "\n");
            }
            //各个成果的失败原因：
            List<LWRequest> lwRequestList = kjjbjResponse.getLwRequestList();
            if (lwRequestList != null && !lwRequestList.isEmpty()) {
                for (LWRequest lwRequest : lwRequestList) {
                    sb.append("  (" + failId++ + ")" + "论文：<<" + lwRequest.getLwtm() + ">> 不合格项：\n");
                    List<String> reason = lwRequest.getFailReason();
                    for (String s : reason) {
                        sb.append("  " + s + ";\n");
                    }

                }
            }
            List<PatentRequest> zlRequestList = kjjbjResponse.getZlRequestList();
            if (zlRequestList != null && !zlRequestList.isEmpty()) {
                for (PatentRequest patentRequest : zlRequestList) {
                    sb.append("  (" + failId++ + ")" + "专利：<<" + patentRequest.getZlmc() + ">> 不合格项：\n");
                    List<String> reason = patentRequest.getFailReason();
                    for (String s : reason) {
                        sb.append("  " + s + ";\n");
                    }
                }
            }
            List<ZZRequest> zzRequestList = kjjbjResponse.getZzRequestList();
            if (zzRequestList != null && !zzRequestList.isEmpty()) {
                for (ZZRequest zzRequest : zzRequestList) {
                    sb.append("  (" + failId++ + ")" + "著作：<<" + zzRequest.getZzmc() + ">> 不合格项：\n");
                    List<String> reason = zzRequest.getFailReason();
                    for (String s : reason) {
                        sb.append("  " + s + ";\n");
                    }
                }
            }
            //完成人员失败的原因：
            List<WcryResonse> wcryResonseList = kjjbAllResponse.getWcryResonseList();
            if (wcryResonseList != null && !wcryResonseList.isEmpty()) {
                for (WcryResonse wcryResonse : wcryResonseList) {
                    WcryShortXM wcryShortXM = wcryResonse.getWcryShortXM();
                    String xm = wcryShortXM.getXm();
                    String xb = wcryShortXM.getXb();
                    String zw = wcryShortXM.getZw();
                    String dwid = wcryShortXM.getDwid();
                    int sum = 0;
                    if (wcryResonse.getOtherJCYJJXM() != null && !wcryResonse.getOtherJCYJJXM().isEmpty()) {
                        sum += wcryResonse.getOtherJCYJJXM().size();
                    }
                    if (wcryResonse.getOtherJSFMJXM() != null && !wcryResonse.getOtherJSFMJXM().isEmpty()) {
                        sum += wcryResonse.getOtherJSFMJXM().size();
                    }
                    if (wcryResonse.getOtherKJJBJXM() != null && !wcryResonse.getOtherKJJBJXM().isEmpty()) {
                        sum += wcryResonse.getOtherKJJBJXM().size();
                    }
                    wcryResonse.getOtherKJJBJXM();
                    sb.append("  (" + failId++ + ")" + "完成人员：" + xm + "," + xb + "," + zw + "," + dwid + ",当前年度参评奖项为:" + sum + "项超过做大限额\n");
                }
            }
            failReasonList.add(sb.toString());
        }
        return failReasonList;
    }

    public String getTJDJMessage(String originStr){
        int anInt = Integer.parseInt(String.valueOf(originStr.charAt(originStr.length() - 1)));
        return  TjdjEnum.getByCode(anInt).getMessage();
    }

}
